import React, { Component } from 'react';
import { connect } from 'react-redux'
import { SwipeAction } from 'antd-mobile'
import actions from '../../../store/actions';
class Index extends Component {
  // 总价
  totalPrice() {
    let price = 0
    this.props.carList.forEach(v => {
      if(v.checked) {
        price += v.price * v.count
      }
    })
    return price
  }
  render() {
    const { carList } = this.props
    return (
      <div>
        {
          carList.length > 0 && carList.map((v, i) => {
            return (
              // 左滑容器 
              <SwipeAction
                key={i}
                rightActions={[
                  {
                    key: 'delete',
                    text: '删除',
                    color: 'danger',
                    // 点击删除回调函数
                    onClick: () => this.props.dispatch(actions.deleteCarList(v))
                  },
                ]}
              >
                {/* 单选  受控组件  分发acitons 修改单个状态 */}
                <input type="checkbox" checked={ v.checked } onChange={ () => this.props.dispatch(actions.switchCarList(v))  }/>
                <dl>
                  <dt><img src={v.url} alt="" /></dt>
                  <dd>
                    <h3>{v.title}</h3>
                    <p>{v.desc}</p>
                    <p>
                      单价： {v.price}
                    </p>
                    <h2>数量</h2>
                    <p>
                      {/* 减少 */}
                      <button onClick={ () => this.props.dispatch(actions.subCarList(v)) }>-</button>
                      {v.count}
                      {/* 添加 */}
                      <button onClick={ () => this.props.dispatch(actions.addCarList(v)) }>+</button>
                    </p>
                  </dd>
                </dl>
              </SwipeAction>

            )
          })
        }

        <h2> 
        <input type="checkbox" 
        // 全选  受控组件  切换所有单选状态
          checked={ this.props.carList.every(v => v.checked) }
          onChange={ (e) => this.props.dispatch(actions.switchCarListAll({ checked: e.target.checked })) }
        /> 全选  总价：{ this.totalPrice() }</h2>

      </div>
    );
  }
}

const mapState = state => state
const mapDiaptch = dispatch => ({ dispatch })

export default connect(mapState, mapDiaptch)(Index);
